package cn.murky.admin.system.biz.mq;

import cn.murky.admin.system.api.enums.SysNoticeTarget;
import cn.murky.admin.system.biz.domain.entity.SysNotice;
import cn.murky.admin.system.biz.endpoint.NoticeEndpoint;
import cn.murky.redismq.RedisMqTemplate;
import lombok.extern.slf4j.Slf4j;
import org.noear.redisx.RedisClient;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.io.IOException;

import static cn.murky.redismq.constant.SysTopicConstant.SYS_NOTICE_TOPIC;

@Component
@Slf4j
public class SysNoticeMqTemplate  implements RedisMqTemplate {
    @Inject
    private RedisClient redisClient;
    @Inject
    private NoticeEndpoint noticeEndpoint;
    public void publish(SysNotice sysNotice){
        String topic = getTopic()+sysNotice.getTarget();
        log.info("[SysNoticeMqTemplate] -> publish 发布系统通知消息 topic:{} msg:{}", topic,sysNotice);
        redisClient.getBus().publish(topic, ONode.stringify(sysNotice));
    }

    @Override
    public boolean subscribe() {
        log.info("[SysNoticeMqTemplate] -> 订阅系统通知主题 -> topic:{}*", getTopic());
        redisClient.getBus().subscribe((topic, msg) -> {
            SysNotice sysNotice = ONode.deserialize(msg, SysNotice.class);
            // 分布式锁,在集群环境下防止重复刷新缓存
            if (redisClient.getLock(STR."\{topic+sysNotice.getId()}:LOCK").tryLock(5)) {
                log.info("[SysNoticeMqTemplate] -> 消费国际化语言包消息 -> topic:{},msg:{}", topic, msg);
                noticeEndpoint.sendSysNotice(sysNotice);
            }
        }, getTopic()+SysNoticeTarget.ADMIN);
        return true;
    }
    @Override
    public String getTopic() {
        return SYS_NOTICE_TOPIC;
    }
}
